package com.larsgard.gedviewer.server.ged;

import genj.gedcom.Gedcom;
import genj.gedcom.Indi;
import genj.io.GedcomReader;
import genj.io.GedcomReaderFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import com.larsgard.gedviewer.server.storage.entities.JDOPerson;

public class GenjGedParser {

    private Gedcom gedcom;
    private Iterator<Indi> indis;
    private int read;
    private int count;

    public GenjGedParser(InputStream gedStream) throws IOException {
	GedcomReader reader = GedcomReaderFactory.createReader(gedStream, null);
	gedcom = reader.read();
	indis = gedcom.getIndis().iterator();
	count = gedcom.getIndis().size();
    }

    public JDOPerson next() {
	if (hasNext()) {
	    read++;
	    return translate(indis.next());
	} else
	    return null;
    }

    public boolean hasNext() {
	return indis.hasNext();
    }

    public JDOPerson translate(Indi indi) {
	JDOPerson person = new JDOPerson();
	person.setIdno(indi.getId());
	person.setFamilyName(indi.getLastName());
	person.setGivenName(indi.getFirstName());
	person.setBirthDate(indi.getBirthAsString());
	person.setDeathDate(indi.getDeathAsString());
	switch (indi.getSex()) {
	case 1:
	    person.setSex("M");
	    break;
	case 2:
	    person.setSex("F");
	    break;
	}
	if (indi.getBiologicalFather() != null) {
	    person.setFatherIdno(indi.getBiologicalFather().getId());
	}
	if (indi.getBiologicalMother() != null) {
	    person.setMotherIdno(indi.getBiologicalMother().getId());
	}

	return person;
    }

    /**
     * Use to restore state if previously interrupted
     */
    public void skip(int read) {
	for (int i = 0; i < read; i++) {
	    indis.next();
	}
	this.read = read;
    }

    public int getRead() {
	return read;
    }

    public int getCount() {
	return count;
    }

}
